document.writeln('<script type="text/javascript"  src="'+root+'/resource/js/cookie.js"></script>');
var tagJsonDataObject ;//服务器端传过来的json串所解析生成的Object 
var availableTags = [];//把所有标签放在一个数组里
$(function (){
	if(tagJsonData != '' ){
		tagJsonDataObject = eval(tagJsonData);
		article_tag_tool.setTagSelectOption(tagJsonDataObject , 'tagLevel1');
		article_tag.initUseMostTagArea();
		LoadUtil.load([
		               [root+'/resource/plugins/jquery_ui/jquery-ui-1.9.2.custom.min.js']//标签输入框智能提示功能依赖的JS
		           ], function() {
						article_tag.autocomplete();
		});
	}
});



(function( window, undefined ) {
	window.article_tag = {

			initUseMostTagArea : function (){
				var cookieStr = cookieUtil.getCookie('useMostTag_cookie_'+channelId +'_'+article_tag.getCharCode(userId));
				if (!cookieStr.length) {return ;}
				var cookieArr = cookieStr.split(',');
				$('#useMostTagArea').append('常用标签：');
				for(var i=0;i< cookieArr.length;i++){
					if(cookieArr[i] && cookieArr != ''){
						//$('#useMostTagArea').append('<a class="c-green-bt go-search-bt" href="javascript:article_tag.clickTagButton(\''+cookieArr[i]+'\')">'+cookieArr[i]+'</a>&nbsp;&nbsp;');
						$('#useMostTagArea').append('&nbsp;&nbsp;<input type="button" class="u-inputBtn" value="'+cookieArr[i]+'" onclick="article_tag.clickTagButton(\''+cookieArr[i]+'\')" />');
					}
				}
			},
			setUseMostTag : function (tags){//把cookie里的数据与本次选中的数据(特殊标签除外)合并后，取最新十个数据形成新的cookie.
				if (!tags.length) {return ;}
				var tagArr = tags.split(',');
				var preCookieStr = cookieUtil.getCookie('useMostTag_cookie_'+channelId+'_'+article_tag.getCharCode(userId));
				for(var i=0;i< tagArr.length;i++){
					if(preCookieStr.indexOf(tagArr[i]) == -1 && $.inArray(tagArr[i] , specialTagArr) == -1 ){//合并数据，特殊标签除外
						preCookieStr = tagArr[i] + ',' + preCookieStr;
					}
				}
				if (preCookieStr.length) {
					preCookieStr = preCookieStr.substring(0 , preCookieStr.length-1);//去掉最后一个','
				}
				var cookieArr = preCookieStr.split(',');
				var cookieStr = '';
				for(var j = 0 ; j < cookieArr.length && j < 10 ; j++){
					if(cookieArr[j]){//若cookieArr[j]不是undefined
						cookieStr += cookieArr[j] + ',';
					}
				}
				//用article_tag.getCharCode对cookie名进行编码是因为tomcat7对中文支持不好，而channelId是中文的
				cookieUtil.setCookie('useMostTag_cookie_'+channelId +'_'+article_tag.getCharCode(userId) ,  cookieStr);//每个频道一份cookie
			},
			autocomplete : function (){//依赖于/resource/plugins/jquery_ui/jquery-ui-1.9.2.custom.min.js
				article_tag.setAvailableTagsFromArr(specialTagArr.concat(tagJsonDataObject));
			    $('#tags' ).autocomplete({
				    	source: function( request, response ) { 		
				    		var  searchKey = request.term.split( /,\s*/ ).pop();
				    		if(searchKey && searchKey.replace(/\s*/g, '') != ''){//传入的数据是空字符串(' ')时不作处理
								//自动保存过程中，忽略","(逗号)
								response( $.ui.autocomplete.filter(availableTags, request.term.split( /,\s*/ ).pop()  ) );
				    		}
						},
						focus: function() {
				                return false;  // 防止插入时，聚焦input框原有的值，造成取代原有值的效果
				        },
				        select: function( event, ui ) {//整段代码是为了选中后，加一个","(逗号)
				        	var terms = this.value.split( /,\s*/ );
			                terms.pop();
			                terms.push( ui.item.value );//加入选中的值
			                // add placeholder to get the comma-and-space at the end
			                terms.push('');
			                this.value = terms.join(',');
			                return false;
				        }
			    });
			},
			clickTagButton : function(tag){
				article_tag_tool.appendToTagsInputs(tag);
			},
			setAvailableTagsFromArr : function(tagJsonDataObject){//把数组里的标签元素放到availableTags数组
				for(var i = 0 , j = tagJsonDataObject.length; i<j ; i++ ){
					var obj = tagJsonDataObject[i];
					article_tag.dispatchSetMethod(obj);
				}
			},
			dispatchSetMethod : function(obj){//根据obj的类型，调度各种设置方法
				if(typeof(obj) == 'string'){
					availableTags.push(obj);
				}else if($.isArray(obj)){
					article_tag.setAvailableTagsFromArr(obj);
				}else if(typeof(obj) == 'object'){
					article_tag.setAvailableTagsFromArrFromObj(obj);
				}
			},
			 setAvailableTagsFromArrFromObj : function(obj){//把对象里的标签放到数组
				for(var a in obj){
					article_tag.dispatchSetMethod(a);
					if(obj[a]){
						article_tag.dispatchSetMethod(obj[a]);
					}
				}
			},
			getCharCode :	function(str){
				var charCode = '';
				for(var i = 0 ; i < str.length ; i++){
					charCode += str.charCodeAt(i);
				}
				return charCode;
			}
	};
	
	window.article_tag_tool = {
			isDuplicateTag : function(str){//判断是否是重复标签;是返回true,否则返回false
				var tags = ','+$('#tags').val()+',';
				return tags.indexOf(','+str+',') > -1;
			},
			appendToTagsInputs : function(tag){//把tag内容放到id为tags的input输入框，重复的标签将不添加
				if(!this.isDuplicateTag(tag)){
					$('#tags').val( $('#tags').val() + tag+ ',');
				}else{//标签已存在，则作提示，并三秒后清除提示
					$('#tagTips').html('标签['+tag+']已存在');
					window.setTimeout(function (){
						$('#tagTips').html('');
					} , 3000);
				}
			},
			setTagSelectOption : function(tagJsonDataObject , tagLevel){//动态设置"发布器普通标签"的下拉框(select)的选择项(option)
				$('#'+tagLevel).show();
				for(var i = 0 , j = tagJsonDataObject.length; i<j ; i++ ){
					var obj = tagJsonDataObject[i];
					if(typeof(obj) == 'string'){
							$('#'+tagLevel).append('<option value="'+i+','+obj+'">'+obj+'</option>');
					}else if(typeof(obj) == 'object'){
						for(var a in obj){
							$('#'+tagLevel).append('<option value="'+i+','+a+'">'+a+'</option>');
							break;
						}
					}
				}
			}
	};
	
	window.article_tagLevel_changer = {
			tagLevel1Object : {},
			tagLevel2Object : {},
			tagLevel3Object : {},
			tagLevel4Object : {},
			changeTagLevel1 : function (){
				//清空二级select和三级select的内容
				this.clearTag('tagLevel2' , 'tagLevel3', 'tagLevel4', 'tagLevel5');
				//清空用按钮形式展示标签的区域
				this.clearButtonArea( 'tagLevel2ButtonArea', 'tagLevel3ButtonArea');
				if($('#tagLevel1').val() == '' ){
					return;
				}
				var tagLevel1Arr = $('#tagLevel1').val().split(',');

				//把一级标签加上
				$('#tagLevel2ButtonArea').append('一级标签： <input type="button" class="u-inputBtn" value="'+tagLevel1Arr[1]+'" onclick="article_tag.clickTagButton(\''+tagLevel1Arr[1]+'\')"  />');
				this.tagLevel1Object = tagJsonDataObject[tagLevel1Arr[0]][tagLevel1Arr[1]];
				if(this.tagLevel1Object && this.tagLevel1Object.constructor == Array){
					if($('#tagLevel2ButtonArea').prev().attr('id') !== 'tagLevel2Blank' ){//添加一列空白行
						$('#tagLevel2ButtonArea').before('<div class="blank10" id="tagLevel2Blank"></div>');
					}
					article_tag_tool.setTagSelectOption( this.tagLevel1Object , 'tagLevel2');//设置二级标签下拉框内容
					$('#tagLevel2ButtonArea').append('&nbsp;&nbsp;二级标签：');
					this.setTagButtonArea(this.tagLevel1Object , 'tagLevel2ButtonArea');
				}
			},
			changeTagLevel2 : function (){
				//清空三级select的内容
				this.clearTag('tagLevel3', 'tagLevel4', 'tagLevel5');
				//清空用按钮形式展示标签的区域
				this.clearButtonArea('tagLevel3ButtonArea');
				if($('#tagLevel2').val() == '' ){
					return;
				}

				
				var level2Arr = $('#tagLevel2').val().split(',');
				this.tagLevel2Object =  this.tagLevel1Object[level2Arr[0]][level2Arr[1]];
				if(this.tagLevel2Object && this.tagLevel2Object.constructor == Array){
					if($('#tagLevel3ButtonArea').prev().attr('id') !== 'tagLevel3Blank' ){//添加一列空白行
						$('#tagLevel3ButtonArea').before('<div class="blank10" id="tagLevel3Blank"></div>');
					}
					article_tag_tool.setTagSelectOption( this.tagLevel2Object , 'tagLevel3');//设置三级标签下拉框内容
					//$('#tagLevel3ButtonArea').before('<div class="blank10"></div>');
					$('#tagLevel3ButtonArea').append('&nbsp;&nbsp;三级标签：');
					this.setTagButtonArea(this.tagLevel2Object , 'tagLevel3ButtonArea');
				}
			},
			changeTagLevel3 : function (){
				//清空三级select的内容
				this.clearTag('tagLevel4', 'tagLevel5');
				if($('#tagLevel3').val() == '' ){
					return;
				}
				var level3Arr = $('#tagLevel3').val().split(',');
				this.tagLevel3Object = this.tagLevel2Object[level3Arr[0]][level3Arr[1]];
				if(this.tagLevel3Object && this.tagLevel3Object.constructor == Array){
					article_tag_tool.setTagSelectOption( this.tagLevel3Object , 'tagLevel4');//设置四级标签下拉框内容
					$('#tagLevel3ButtonArea').append('&nbsp;&nbsp;四级标签：');
					this.setTagButtonArea(this.tagLevel3Object , 'tagLevel3ButtonArea');
				}
			},
			changeTagLevel4 : function (){
				//清空三级select的内容
				this.clearTag('tagLevel5');
				if($('#tagLevel4').val() == '' ){
					return;
				}
				
				var level4Arr = $('#tagLevel4').val().split(',');
				this.tagLevel4Object = this.tagLevel3Object[level4Arr[0]][level4Arr[1]];
				if(this.tagLevel4Object && this.tagLevel4Object.constructor == Array){
					article_tag_tool.setTagSelectOption( this.tagLevel4Object , 'tagLevel5');//设置五级标签下拉框内容
					$('#tagLevel3ButtonArea').append('&nbsp;&nbsp;五级标签：');
					this.setTagButtonArea(this.tagLevel4Object , 'tagLevel3ButtonArea');
				}
			},
			changeTagLevel5 : function (){
				if($('#tagLevel5').val() == '' ){
					return;
				}
				var level5Arr = $('#tagLevel5').val().split(',');
				article_tag_tool.appendToTagsInputs(level5Arr[1]);
			},
			clearTag : function (){//清空标签下拉框内容并把下拉框隐藏
				for (var i=0;i<arguments.length;i++) {
					$('#'+arguments[i]).hide();
					$('#'+arguments[i]).empty();
					$('#'+arguments[i]).append('<option value="">----请选择分类----</option>');
				}
			},
			clearButtonArea :  function (){//清空用按钮形式展示标签的区域
				for (var i=0;i<arguments.length;i++) {
					$('#'+arguments[i]).html('');
				}
			},
			setTagButtonArea : function(tagJsonDataObject , tagLevel){
				for(var i = 0 , j = tagJsonDataObject.length; i<j ; i++ ){
					var obj = tagJsonDataObject[i];
					if(typeof(obj) == 'string'){
							//$('#'+tagLevel).append('<a class="c-green-bt go-search-bt" style="margin-top: 10px"  href="javascript:article_tag.clickTagButton(\''+obj+'\')">'+obj+'</a>&nbsp;&nbsp;');
    						$('#'+tagLevel).append('&nbsp;&nbsp;<input type="button" class="u-inputBtn" value="'+obj+'" onclick= "article_tag.clickTagButton(\''+obj+'\')" />');
					}else if(typeof(obj) == 'object'){
						for(var a in obj){
							//$('#'+tagLevel).append('<a class="c-green-bt go-search-bt" style="margin-top: 10px" href="javascript:article_tag.clickTagButton(\''+a+'\')">'+a+'</a>&nbsp;&nbsp;');
							$('#'+tagLevel).append('&nbsp;&nbsp;<input type="button" class="u-inputBtn" value="'+a+'"  onclick = "article_tag.clickTagButton(\''+a+'\')" />');
							break;
						}
					}
				}
			}
	};
})(window);
